package com.pr.wms.wechat.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.pr.wms.exception.WechatException;
import com.pr.wms.model.Category;
import com.pr.wms.util.GsonUtils;
import com.wechat.sdk.propertie.WeChatGlobal;
import com.wechat.sdk.util.WeChatUtil;

@Service("wechatCategoryService")
public class WechatCategoryService {
	protected static final Logger log = LoggerFactory.getLogger(WechatCategoryService.class);

	/**
	 * 获取用户信息
	 * 
	 * @param accessToken
	 *            接口访问凭证
	 * @param cateId
	 *            用户标识
	 * @return List<Category>
	 * @throws Exception
	 */
	public static List<Category> getCategory(String accessToken, int cateId) throws Exception {
		List<Category> cateList = new ArrayList<Category>();
		// 拼接请求地址
		String requestUrl = WeChatGlobal.MERCHANT_CATEGORY_GETSUB;
		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", String.valueOf(cateId));
		// 获取用户信息
		String jsonStr = WeChatUtil.httpsRequest(requestUrl, "GET", null);
		if (null != jsonStr) {
			Map jsonMap = GsonUtils.fromJson(jsonStr);
			// 错误码
			int errcode = Integer.valueOf((String) jsonMap.get("errcode"));
			if (errcode != 0) {
				String errmsg = (String) jsonMap.get("errmsg");
				throw new WechatException(errcode, errmsg);
			}
			List<Map<String, String>> cList = (List) jsonMap.get("cate_list");
			for (Map<String, String> cMap : cList) {
				Category cate = new Category();
				cate.setCateId(cateId);
				cate.setId(Integer.valueOf(cMap.get("id")));
				cate.setName(cMap.get("name"));
				cateList.add(cate);
			}
		}
		return cateList;
	}
}
